<?php


namespace app\controller;

use app\BaseController;
use app\model\Address;
use app\model\Cart;
use app\model\Cat;
use app\model\Menu;
use app\model\Goods;
use app\model\Order;
use app\model\User as UserModel;
use think\facade\Db;
use think\facade\View;
use think\facade\Session;
use think\facade\Request;

class User extends BaseController
{
    public function index(){

        $this->isLogin();

        $title = '商城首页';
        $login = '黄定鑫';

        $Db = new Goods();
        $right = $Db->getGoods();
        $rightList = $right;

        $Db1 = new Menu();
        $left = $Db1->getMenu();

        $Db2 = new Cart();
        $cart = $Db2->getQuantity(Session::get('user_id'));

        View::assign([
            'title' => $title,
            'login' => $login,
            'right' => $right,
            'cart' => $cart,
            'rightList' => $rightList,
            'left' => $left,
        ]);
        return View::fetch();
    }

    public function login(){
        $title = '登录';
        $this->logined();

        View::assign('title',$title);
        return View::fetch();
    }

    public function register(){
        if(Request::method() == 'POST'){
            $data = Request::param();

            $password = sha1($data['password']);
            unset($data['password']);
            $data['password'] = $password;

            $db = new UserModel();
            $res = $db->register($data);
            if ($res){
                return ['status'=>1,'message'=>$res];
            }else{
                return ['status'=>0,'message'=>$res];
            }
        }else{
            View::assign('title','注册');
            return View::fetch();
        }
    }

    public function checkRegisterTel(){
//        $data = Request::param();
//        $rule = [
//            'name|姓名' => 'require|length:2,20',
//            'tel|电话'  => 'require|mobile|unique:user',
//            'password|密码'  => 'require|length:4,20|alphaNum|confirm:confirm'
//        ];
//        $result = $this->validate($data,$rule);
//        if($result){
//            return ['status'=>1,'message'=>'√可用'];
//        }else{
//            return ['status'=>0,'message'=>$result];
//        }
        $tel = Request::param('tel');

        $db = new UserModel();
        $res = $db->checkTel($tel);
        if ($res == false){
            return ['status'=>0, 'message'=>'×电话已存在'];
        }else{
            return ['status'=>1,'message'=>'√手机号可用'];
        }
    }

    public function checkRegisterConfirm(){
        $password = Request::param('password');
        $confirm = Request::param('confirm');

        if ($password == $confirm && $password != null){
            return ['status'=>1, 'message'=>'√密码正确'];
        }else{
            return ['status'=>0,'message'=>'×两次密码不一致'];
        }
    }

    public function loginOut(){
        if (Session::has('user_id')){
            Session::clear();
            $this->success('退出登录成功','user/login');
        }else{
            $this->error('未登录不能退出','user/login');

        }

    }

    public function loginCheck(){
        if (Request::isAjax()){
            $data = Request::param();

            $rule = [
                'tel' => 'require',
                'password' =>'require'
            ];
            $result = $this->validate($data,$rule);

            if($result != true){
                return ['status' =>0,'message'=>$result];
            }else{
                $Db = new UserModel();
                $res = $Db->checkUser($data);

                if($res == null){
                    return ['status'=>0,'message'=>$res];
                }else{
                    Session::set('user_id',$res['id']);
                    Session::set('user_name',$res['name']);
                    return ['status'=>1,'message'=>'suc'];
                }
            }

        }else{
            return ['status'=>0,'message'=>'请求类型错误'];
        }
    }

    public function addCart(){
        $data = Request::param();
        $db = new Cart();
        $res = $db->checkCart($data['goods_id']);
//        halt($res);
        if (!$res){
            $data['user_id'] = Session::get('user_id');
            $data['create_time'] = time();
            $data['quantity'] = 1;
            $result = $db->addCart($data);
            if ($result){
                $Db = new Goods();
                $Db->updateStock($data['goods_id']);
                return ['status'=>1,'message'=>'增加成功'];
            }
            else {
                 return ['status' => 0, 'message' => 'fail'];
            }
        }else{
            $Db = new Goods();
            $Db->updateStock($data['goods_id']);
            $db->updateQuantity($data['goods_id']);
            return ['status'=>1,'message'=>'数量+1'];
        }

    }

    public function useraddr(){
        $this->isLogin();
        $title = '地址管理';
        $Db1 = new Menu();
        $left = $Db1->getMenu();


        $db = new Address();

        $right = $db->getAll(Session::get('user_id'));

        View::assign([
            'title' => $title,
            'left' => $left,
            'right' => $right,
        ]);

        return View::fetch();
    }

    public function addaddress(){
        if (Request::method() == "POST"){
            $data = Request::param();
            $data['user_id'] = Session::get("user_id");

            $db = new Address();
            $res = $db->addAdd($data);
            if ($res){
                echo json_encode(['status'=>1,'message'=>'suc']);
            }else{
                echo json_encode(['status'=>0,'message'=>'fail']);
            }
        }else{
            return View::fetch();
        }


    }

    public function addredit(){
        if (Request::method() == 'POST'){
            $data = Request::param();
            $db1 = new Address();
            $res = $db1->updateAddr($data);
            if ($res){
                return ['status'=>1,'message'=>'suc'];
            }else{
                return ['status'=>0,'message'=>'fail'];
            }
        }else{
            $id = Request::param('id');
            $db = new Address();
            $res = $db->getOne($id);

            View::assign('address',$res);
            return View::fetch();
        }
    }

    public function delAddr(){
        $id = Request::param('id');
        $db = new Address();
        $res = $db->delOne($id);
        if ($res){
            return ['status'=>1,'message'=>'suc'];
        }else{
            return ['status'=>0,'message'=>'fail'];
        }
    }

    public function upDefault(){
        $id =Request::param('addid');
        $db = new Address();
        $res = $db->upDefault($id);
        if ($res){
            return ['status'=>1,'message'=>'suc'];
        }else{
            return ['status'=>0,'message'=>'fail'];
        }
    }

    public function shopcart(){
        $id = Session::get('user_id');
//        halt($id);
        //多表查询
        $right = Db::name('goods')->alias('g')//别名
            ->join('cart','g.id=cart.goods_id')
            ->where('cart.user_id',$id)
            ->order('cart.goods_id')
            ->paginate(10);

        $rightList = $right;
//        halt(var_dump($right));

        View::assign([
            'title'=>'购物车',
            'count'=>0,
            'price'=>0,
            'right'=>$right,
            'rightList'=>$rightList,
            'left'=>(new Menu())->getMenu(),
        ]);

        return View::fetch();
    }

    public function orderman(){
//        $db = new Order();
//        $right = $db->getAll(Session::get('user_id'));
        //多表查询
        $right = Db::name('goods')->alias('good')//别名
        ->join('order','good.id=order.goods_id')
            ->where('order.user_id',Session::get('user_id'))
            ->where('is_delete',0)
            ->order('order.goods_id')
            ->paginate(10);


        View::assign([
            'title'=>'订单管理',
            'right'=>$right,
            'count'=>0,
            'rightList'=>$right,
            'left'=>(new Menu())->getMenu(),
        ]);

        return View::fetch();
    }

    public function delOneOnCart(){
        $goods_id = Request::param('goods_id');
        $quantity = Request::param('quantity');
        $db = new Cart();
        $db1 = new Goods();
        $result = $db->delOne($goods_id);
        $db1->recovery($goods_id,$quantity);
        if ($result){
            return ['status'=>1,'message'=>'移除购物车成功'];
        }else{
            return ['status'=>0,'message'=>$result];
        }
    }

    public function buyOne(){
        $data = Request::param();
        $data['user_id'] = Session::get('user_id');
        $data['status'] = rand(0,2);

        $db1 = new Cart();
        $res1 = $db1->delOne($data['goods_id']);

        $db2 = new Order();
        $res2 = $db2->buyOne($data);

        if ($res1 && $res2){
            return ['status'=>1,'message'=>'suc'];
        }else{
            return ['status'=>0,'message'=>$res1.'1'.$res2];
        }

    }

    public function buyAll(){
        //获取所有购物车的商品id
        $db = new Cart();
        $data = ($db->buyAll())->toArray();

        //判断购物车是否有数据
        if ($data){
            //为每个商品增加订单的状态值
            foreach ($data as $key=>$value){
                $data[$key]['status'] = rand(0,2);
                $data[$key]['user_id'] = Session::get('user_id');
            }

            //获取现有的商品id
            $db1 = new Goods();
            $goods_data = $db1->getAllId();

            //为data数组增加 每个商品的总金钱数
            foreach ($goods_data as $key=>$value){
                foreach ($data as $key1=>$value1){
                    if ($goods_data[$key]['id'] == $data[$key1]['goods_id']){
                        $data[$key1]['total_money'] = $goods_data[$key]['price'] * $data[$key1]['quantity'];
                    }
                }
            }

            //开始操作 新发现的方法
            $db2 = new Order;
            $res = $db2->saveAll($data);
            if ($res){
                return ['status'=>1,'message'=>$res];
            }else{
                return ['status'=>0,'message'=>$res];
            }
        }else{
            return ['status'=>0,'message'=>'买个锤子'];
        }
    }

    public function cancel(){
        $data = Request::param();

        $db = new Goods();
        $res = $db->cancel($data['goods_id'],$data['quantity']);

        $Db = new Order();
        $res1 = $Db->cancel($data['id']);

        if ($res && $res1){
            return ['status'=>1,'message'=>'suc'];
        }else{
            return ['status'=>0,'message'=>$res];
        }
    }

    //删除订单
    public function delOrder(){
        $id = Request::param('id');
        $Db = new Order();
        $res = $Db->hiddenOrder($id);
        if ($res){
            return ['status'=>1,'message'=>'suc'];
        }else{
            return ['status'=>0,'message'=>$res];
        }
    }

    //订单恢复
    public function orderrec(){
        if (Request::method() == 'GET'){

            $right = Db::name('goods')->alias('good')//别名
            ->join('order','good.id=order.goods_id')
                ->where('order.user_id',Session::get('user_id'))
                ->where('is_delete',1)
                ->order('order.goods_id')
                ->paginate(10);

            View::assign('right',$right);
            View::assign('title','订单恢复');

            return View::fetch();
        }else{
            $id = Request::param('id');
            $res = (new Order())->recOrder($id);
            if ($res){
                return ['status'=>1,'message'=>'恢复成功'];
            }else{
                return ['status'=>0,'message'=>$res];
            }
        }
    }

    public function orderDel(){
        $id = Request::param('id');
        $res = (new Order())->delOrder($id);
        if ($res){
            return ['status'=>1,'message'=>'删除成功,该操作不可逆'];
        }else{
            return ['status'=>0,'message'=>$res];
        }
    }


}